<template>
  <div class="supply-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" ref="searchFormRef">
          <el-form-item label="供货商编号">
            <el-input v-model="searchForm.supplyNum" placeholder="请输入供货商编号" clearable />
          </el-form-item>
          <el-form-item label="供货商名称">
            <el-input v-model="searchForm.supplyName" placeholder="请输入供货商名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="content-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">供货商列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增供货商
          </el-button>
        </div>
      </template>

      <el-table 
        :data="tableData" 
        v-loading="loading"
        border 
        stripe
        style="width: 100%"
      >
        <el-table-column prop="supplyNum" label="供货商编号" width="120" />
        <el-table-column prop="supplyName" label="供货商名称" width="180" />
        <el-table-column prop="supplyIntroduce" label="供货商介绍" show-overflow-tooltip />
        <el-table-column prop="concat" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="140" />
        <el-table-column prop="address" label="地址" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增供货商' : '编辑供货商'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="供货商编号" prop="supplyNum">
          <el-input v-model="form.supplyNum" placeholder="请输入供货商编号" />
        </el-form-item>
        <el-form-item label="供货商名称" prop="supplyName">
          <el-input v-model="form.supplyName" placeholder="请输入供货商名称" />
        </el-form-item>
        <el-form-item label="供货商介绍" prop="supplyIntroduce">
          <el-input
            v-model="form.supplyIntroduce"
            type="textarea"
            rows="3"
            placeholder="请输入供货商介绍"
          />
        </el-form-item>
        <el-form-item label="联系人" prop="concat">
          <el-input v-model="form.concat" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Search, Refresh, Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { get, post, put, del } from '@/common';

// 搜索表单
const searchForm = reactive({
  supplyNum: '',
  supplyName: ''
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 表单相关
const dialogVisible = ref(false);
const dialogType = ref('add');
const formRef = ref(null);
const form = reactive({
  supplyId: '',
  supplyNum: '',
  supplyName: '',
  supplyIntroduce: '',
  concat: '',
  phone: '',
  address: ''
});

// 表单校验规则
const rules = {
  supplyNum: [{ required: true, message: '请输入供货商编号', trigger: 'blur' }],
  supplyName: [{ required: true, message: '请输入供货商名称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
};

// 获取供货商列表
const getSupplyList = async () => {
  loading.value = true;
  try {
    const params = {};
    if (searchForm.supplyNum) params.supplyNum = searchForm.supplyNum;
    if (searchForm.supplyName) params.supplyName = searchForm.supplyName;
    
    // 获取所有供货商列表
    const result = await get('/supply/list');
    
    if (result && result.code === 200 && Array.isArray(result.data)) {
      tableData.value = result.data;
    } else if (result && result.code === 200 && result.data) {
      // 如果返回单个对象，转换为数组
      tableData.value = [result.data];
    } else {
      tableData.value = [];
      ElMessage.warning('暂无数据');
    }
  } catch (error) {
    console.error('Failed to fetch supply list:', error);
    ElMessage.error('获取供货商列表失败');
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = async () => {
  loading.value = true;
  try {
    // 如果供货商编号为空，则获取所有列表
    if (!searchForm.supplyNum) {
      getSupplyList();
      return;
    }
    
    const result = await get(`/supply/${searchForm.supplyNum}`);
    
    if (result && result.code === 200 && result.data) {
      tableData.value = [result.data];
    } else {
      tableData.value = [];
      ElMessage.warning('未找到相关供货商');
    }
  } catch (error) {
    console.error('Failed to search supply:', error);
    ElMessage.error('查询失败');
    tableData.value = [];
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchForm.supplyNum = '';
  searchForm.supplyName = '';
  getSupplyList();
};

// 新增供货商
const handleAdd = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
  Object.keys(form).forEach(key => form[key] = '');
};

// 编辑供货商
const handleEdit = (row) => {
  dialogType.value = 'edit';
  dialogVisible.value = true;
  Object.assign(form, row);
};

// 删除供货商
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该供货商吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await del(`/supply/delete/${row.supplyNum}`);
      ElMessage.success('删除成功');
      getSupplyList();
    } catch (error) {
      console.error('Failed to delete supply:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await post('/supply/add', form);
          ElMessage.success('添加成功');
        } else {
          await put('/supply/update', form);
          ElMessage.success('更新成功');
        }
        dialogVisible.value = false;
        getSupplyList();
      } catch (error) {
        console.error('Failed to submit form:', error);
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
      }
    }
  });
};

// 初始化
onMounted(() => {
  getSupplyList();
});
</script>

<style scoped>
.supply-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.content-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
  margin-right: 18px;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-input__wrapper) {
  width: 220px;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}
</style> 